package com.syncomponents.convert.impl;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.util.Map;

import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.stream.StreamSource;

import org.apache.commons.lang3.StringUtils;
import org.perf4j.aop.Profiled;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import com.syncomponents.convert.MessageConvertHandler;
import com.syncomponents.core.ServiceException;
import com.syncomponents.xml.XsltHelper;

/**
 * xslt 消息转换实现类
 * 
 * @author sunkey
 * @date Jan 16, 2014
 */
@Component(value = "xsltConvertHandler")
public class XsltConvertHandler implements MessageConvertHandler {

    @Override
    @Profiled
    public Object handle(Object origin, String xlstPath, Map<String, Object> paramMap) {

        Assert.notNull(origin);

        if (StringUtils.isBlank(xlstPath) || !(origin instanceof String)) {
            return null;
        }

        URL url = this.getClass().getResource(xlstPath);
        StringReader sr = new StringReader(origin.toString());
        Source xmlSource = new StreamSource(sr);

        Source xsltSource;
        try {
            xsltSource = new StreamSource(url.openStream(), xlstPath);
        } catch (IOException e) {
            throw new ServiceException(e.getMessage(), e);
        }

        StringWriter sw = new StringWriter();
        try {
            XsltHelper.transform(xmlSource, xsltSource, sw, paramMap);
        } catch (TransformerException e) {
            throw new ServiceException(e.getMessage(), e);
        }

        return sw.toString();
    }

}
